package com.power.project.dao.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.power.project.model.P_project;
import com.power.project.model.pageInfo.P_projectPageInfo;
import com.power.project.model.pageInfo.P_projectuserPageInfo;
import com.power.project.model.vo.UserBaseVO;
import com.power.project.utils.PageHelperUtil;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import com.power.project.dao.P_projectDaoCustom;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

import static com.power.project.dao.impl.Ww_userDaoImpl.BLANK_STRING;

/**
 * 项目 持久层实现(hibernate)
 */

@Repository
public class P_projectDaoImpl implements P_projectDaoCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<UserBaseVO> queryUsersByPid(P_projectuserPageInfo pageInfo) {

        StringBuilder sql = new StringBuilder("select u.userid as userId ,u.name, u.mobile, u.avatar " +
                "from p_project p " +
                "         left join p_projectuser pu on p.id = pu.projectid " +
                "         left join ww_user u on pu.wwuserid = u.userid");

        sql.append(" where p.deleted = 0 and p.id = " + pageInfo.getF_projectid());

        Query query = entityManager.createNativeQuery(sql.toString());
        NativeQueryImpl nativeQuery = query.unwrap(NativeQueryImpl.class);
        nativeQuery.setResultTransformer(Transformers.aliasToBean(UserBaseVO.class));
        // 查询总数
        pageInfo.setAllcount(query.getResultList().size());
        // 分页
        List<UserBaseVO> resultList = new ArrayList<>();
        if (pageInfo.getAllcount() > 0) {
            int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
            resultList = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
        }
        return resultList;
    }

    @Override
    public Page<P_project> findPage(P_projectPageInfo pageInfo, Pageable pageable) {
        //把分页转成list
        StringBuilder dataSql = new StringBuilder("SELECT version, id, projectname, clientcompany, finished, mgruserids, tenantid, p1.projectcode " +
                "FROM p_project AS p1 " +
                "         JOIN (SELECT projectcode, MAX(version) as max_version " +
                "               FROM p_project " +
                "               where deleted = 0 " +
                "               GROUP BY projectcode) AS p2 " +
                "              ON p1.projectcode = p2.projectcode AND p1.version = p2.max_version ");

        StringBuilder countSql = new StringBuilder("SELECT count(*) " +
                "FROM p_project AS p1 " +
                "         JOIN (SELECT projectcode, MAX(version) as max_version " +
                "               FROM p_project " +
                "               where deleted = 0 " +
                "               GROUP BY projectcode) AS p2 " +
                "              ON p1.projectcode = p2.projectcode AND p1.version = p2.max_version ");

        StringBuilder whereSql = new StringBuilder("where p1.deleted = 0 and p1.tenantid = :tenantid").append(BLANK_STRING);
        StringBuilder orderSql = new StringBuilder("order by finished desc");

        if(StrUtil.isNotBlank(pageInfo.getF_projectname())){
            whereSql.append("and p1.projectname like concat('%',:projectname,'%')").append(BLANK_STRING);
        }
        if(CollUtil.isNotEmpty(pageInfo.getF_ids())){
            whereSql.append("and p1.id in ("+
                    String.join(", ", pageInfo.getF_ids().stream().map(Object::toString).toArray(String[]::new))+
                    ")").append(BLANK_STRING);
        }


        dataSql.append(whereSql);
        dataSql.append(orderSql);
        countSql.append(whereSql);
        //创建本地sql查询
        Query dataQuery = entityManager.createNativeQuery(dataSql.toString());
        Query countQuery = entityManager.createNativeQuery(countSql.toString());

        //设置参数
        dataQuery.setParameter("tenantid",pageInfo.getF_tenantid());
        countQuery.setParameter("tenantid",pageInfo.getF_tenantid());
        if(StrUtil.isNotBlank(pageInfo.getF_projectname())){
            dataQuery.setParameter("projectname",pageInfo.getF_projectname());
            countQuery.setParameter("projectname",pageInfo.getF_projectname());
        }
        return PageHelperUtil.getPage(pageable,dataQuery,countQuery, P_project.class);
    }
}